<?php

include '../config/config.php';
include 'Zend/Db.php';

$db = Zend_Db::factory('Pdo_Mysql', $dbConfig);

function process_student_file ($file) {

	$handle = fopen($file, 'r');
	
	while(($line = fgetcsv($handle, 250, ',')) !== false) {
		
		$data_array[] = array(
			'mod_id'	=> $line[0],
			'tut_id'	=> $line[1],
			'stu_id'	=> $line[2],
			'sname'		=> $line[3],
			'fname'		=> $line[4],
			'email'		=> $line[5],
			'feed'		=> $line[6]
		);
		
		// build a hash of the tutorial numbers (overwrite duplicates)
		$tut_id = $line[1];
		$tut_array["$tut_id"] = $tut_id;
		
	   }
	  
 	fclose($handle);
	return array($data_array, $tut_array);

}

// list ($data, $tut) = process_student_file ('./upload/student_data.csv');
list($data, $tut) = process_student_file ($names);


//echo $mod_id;

// get the pk of the module from the modules table
$mod_id = $data[0]['mod_id'];
$pk_mod_id = $db->fetchOne("SELECT module_id FROM modules WHERE module_code = '$mod_id'");

// insert all tutorial into tutorials table setting $pk_mod_id to fk

foreach($tut as $key=>$value){

$fields = array(
    'tutorial_id'		=> '',
    'tutorial_title' 	=> 'Tutorial '.$value,
    'fk_module_id'		=> $pk_mod_id

);

$db->insert('tutorials', $fields);

// get the current auto_increment value from the tutorial insert
$pk_tut_id = $db->lastInsertId();
$pk_tut_id_array["$value"] = $pk_tut_id;

}

// print_r($pk_tut_id_array);

// for each item in $pk_tut_id_array
foreach ($pk_tut_id_array as $key=>$value) {
	foreach($data as $key1=>$value1) {
		if ($value1['tut_id'] == $key) {
			
			$student_record = array(
				'student_id'		=> '',
				'student_code'		=> $value1['stu_id'],
				'sname'				=> $value1['sname'],
				'fname'				=> $value1['fname'],
				'email'				=> $value1['email'],
				'fk_tutorial_id'	=> $value
			);
		
			$db->insert('students', $student_record);
			
			// get the current auto_increment value from the student insert
			$pk_student_id = $db->lastInsertId();
			
			//insert feedurl to the blog table
			$blog_record = array(
				'blog_id'		=> '',
				'feedurl'		=> $value1['feed'],
				'fk_student_id'	=> $pk_student_id
				
			);
			
			$db->insert('blogs', $blog_record);
		}
	}
}

echo count($data).' records successfully processed!';

// echo "OK";


?>